package org.light.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.utils.DomainUtil;
import org.light.utils.InterVarUtil;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class CloneAll extends Verb implements EasyUIPositions {

	@Override
	public Method generateDaoImplMethod() throws Exception {
		return null;
	}

	@Override
	public Method generateDaoMethodDefinition() {
		return null;
	}

	@Override
	public Method generateServiceMethodDefinition() {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("CloneAll"+StringUtil.capFirst(this.domain.getPlural()));
			method.addSignature(new Signature(1,InterVarUtil.DB.ids.getVarName(),InterVarUtil.DB.ids.getVarType()));
			return method;
		}
	}

	@Override
	public Method generateServiceImplMethod() throws ValidateException{
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("CloneAll"+StringUtil.capFirst(this.domain.getPlural()));
			method.addSignature(new Signature(1, "ids", new Type("Vec<i64>")));
			method.setReturnType(new Type("Result<u64, sqlx::Error>"));
			
			Clone clone = new Clone(this.domain);
			
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"let app_state = init_db();"));
			sList.add(new Statement(3000L,1,"let vecter_iterator = ids.iter();"));
			sList.add(new Statement(4000L,1,"for "+this.domain.getSnakeDomainName()+"_id in vecter_iterator {"));
			sList.add(new Statement(5000L,2,StringUtil.getSnakeName(clone.getVerbName())+"(*"+this.domain.getSnakeDomainName()+"_id).await;"));
			sList.add(new Statement(6000L,1,"}"));
			sList.add(new Statement(7000L,1,"Ok(0)"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	
	public CloneAll(){
		super();
		this.setLabel("批克隆");
	}	
	
	public CloneAll(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.denied = domain.isVerbDenied("CloneAll");
		this.setVerbName("CloneAll"+StringUtil.capFirst(this.domain.getPlural()));
		this.setLabel("批克隆");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("CloneAll");
	}

	@Override
	public Method generateControllerMethod() throws ValidateException{
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("CloneAll"+StringUtil.capFirst(this.domain.getPlural()));
			method.addSignature(new Signature(1,"Form(ids_request)","Form<IdsRequest>"));
			method.setReturnType(new Type("String"));
			
			List<Writeable> sList = new ArrayList<Writeable>();

			sList.add(new Statement(1000L,1,"let ids = ids_request.ids;"));
			sList.add(new Statement(2000L,1,"let string_ids:Vec<&str> = ids.split(',').collect();"));
			sList.add(new Statement(3000L,1,"let mut "+this.domain.getDomainId().getSnakeFieldName()+"s:Vec<i64> = Vec::new();"));
			sList.add(new Statement(4000L,0,""));
			sList.add(new Statement(5000L,1,"let vecter_iterator = string_ids.iter();"));
			sList.add(new Statement(6000L,1,"for "+this.domain.getDomainId().getSnakeFieldName()+" in vecter_iterator {"));
			sList.add(new Statement(7000L,2,""+this.domain.getDomainId().getSnakeFieldName()+"s.push("+this.domain.getDomainId().getSnakeFieldName()+".parse::<i64>().unwrap());"));
			sList.add(new Statement(8000L,1,"}"));
			sList.add(new Statement(9000L,0,""));
			sList.add(new Statement(10000L,1,"let result = service_"+StringUtil.getSnakeName(this.getVerbName())+"("+this.domain.getDomainId().getSnakeFieldName()+"s).await;"));
			sList.add(new Statement(11000L,1,"match result {"));
			sList.add(new Statement(12000L,2,"Err(_) => {"));
			sList.add(new Statement(13000L,3,"println!(\"Error!\");"));
			sList.add(new Statement(14000L,3,"r#\"{  \"rows\": null,  \"success\": true}\"#.to_string()"));
			sList.add(new Statement(15000L,2,"},"));
			sList.add(new Statement(16000L,2,"Ok(result) => {"));
			sList.add(new Statement(17000L,3,"let mut map = Map::new();"));
			sList.add(new Statement(18000L,3,"map.insert(\"success\".to_string(), Value::from(true));"));
			sList.add(new Statement(19000L,3,"map.insert("));
			sList.add(new Statement(20000L,4,"\"rows\".to_string(),"));
			sList.add(new Statement(21000L,4,"Value::from(\"\"),"));
			sList.add(new Statement(22000L,3,");"));
			sList.add(new Statement(23000L,3,""));
			sList.add(new Statement(24000L,3,"let resultjson = serde_json::to_string_pretty(&map).unwrap();"));
			sList.add(new Statement(25000L,3,"//println!(\"{}\", resultjson);"));
			sList.add(new Statement(26000L,3,"return resultjson;"));
			sList.add(new Statement(27000L,2,"}"));
			sList.add(new Statement(28000L,1,"}"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("cloneAll"+domain.getCapFirstPlural());
			StatementList sl = new StatementList();
			sl.add(new Statement(1000,0, "{"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(2000, 1, "text:'CloneAll',"));
			}else {
				sl.add(new Statement(2000,1, "text:'批克隆',"));
			}
			sl.add(new Statement(3000,1, "iconCls:'icon-add',"));
			sl.add(new Statement(4000,1, "handler:function(){ "));
			sl.add(new Statement(5000,2, "var rows = $(\"#dg\").datagrid(\"getChecked\");"));
			sl.add(new Statement(6000,2, "if (rows == undefined || rows == null || rows.length == 0 ){"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(7000,3, "$.messager.alert(\"Alert\",\"Please choose record!\",\"warning\");"));
			}else {
				sl.add(new Statement(7000,3, "$.messager.alert(\"警告\",\"请选定记录！\",\"warning\");"));
			}
			sl.add(new Statement(8000,3, "return;"));
			sl.add(new Statement(9000,2, "}"));
			sl.add(new Statement(10000,2, "var ids = \"\";"));
			sl.add(new Statement(11000,2, "for(var i=0;i<rows.length;i++){"));
			sl.add(new Statement(12000,3, "ids += rows[i][\""+domain.getDomainId().getLowerFirstFieldName()+"\"];"));
			sl.add(new Statement(13000,3, "if (i < rows.length-1) ids += \",\";"));
			sl.add(new Statement(14000,2, "}"));
			sl.add(new Statement(15000,2, "cloneAll"+domain.getCapFirstPlural()+"(ids);"));
			sl.add(new Statement(16000,1, "}"));
			sl.add(new Statement(17000,0, "}"));
			block.setMethodStatementList(sl);
			return block;			
		}
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			Var ids = new Var("ids",new Type("var"));
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName("cloneAll"+StringUtil.capFirst(domain.getPlural()));
			Signature s1 = new Signature();
			s1.setName(ids.getVarName());
			s1.setPosition(1);
			s1.setType(new Type("var"));
			method.addSignature(s1);
			
			StatementList sl = new StatementList();
			sl.add(new Statement(1000,1, "$.ajax({"));
			sl.add(new Statement(2000,2, "type: \"post\","));
			sl.add(new Statement(3000,3, "url: \"../"+this.domain.getControllerPackagePrefix()+domain.getLowerFirstDomainName()+domain.getControllerNamingSuffix()+"/cloneAll"+domain.getCapFirstPlural()+"\","));
			sl.add(new Statement(4000,3, "data: {"));
			sl.add(new Statement(5000,4, "ids:ids"));
			sl.add(new Statement(6000,3, "},"));
			sl.add(new Statement(7000,3, "dataType: 'json',"));
			sl.add(new Statement(8000,3, "success: function(data, textStatus) {"));
			sl.add(new Statement(9000,4, "$(\"#dg\").datagrid(\"load\");"));
			sl.add(new Statement(10000,3, "},"));
			sl.add(new Statement(11000,3, "complete : function(XMLHttpRequest, textStatus) {"));
			sl.add(new Statement(12000,2, "},"));
			sl.add(new Statement(13000,2, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sl.add(new Statement(14000,3, "alert(\"Error:\"+textStatus);"));
			sl.add(new Statement(15000,3, "alert(errorThrown.toString());"));
			sl.add(new Statement(16000,2, "}"));
			sl.add(new Statement(17000,1, "});"));
			
			method.setMethodStatementList(sl);
			return method;		
		}
	}

}
